<template>
  <el-dialog v-model="dialogFormVisible" title="编辑店铺" width="600">
    <el-form :model="shopForm" ref="shopFormRef" :rules="rules" status-icon>
      <el-form-item label="店铺名" label-width="70px" prop="name">
        <el-input v-model="shopForm.name" />
      </el-form-item>
    </el-form>
    <el-button @click="shopEdit(shopFormRef)">确认更改</el-button>
  </el-dialog>
</template>
  
<script lang="ts" setup>
import { deliverOrderByIdAndJwt } from "../../api/order/"
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getShopById } from "../../api/shop";

const id = ref(0);

//打开本ShopEdit页
const dialogFormVisible = ref(false)
const openDialog = (orderId: number) => {
  dialogFormVisible.value = true
  id.value = orderId
}
defineExpose({
  openDialog
})


// 商店表单
interface shopType {
  name: string
}
const shopFormRef = ref<FormInstance>()
//创建商店表单数据
const shopForm = reactive<shopType>({
  name: ''
})
const rules = reactive<FormRules<shopType>>({
  name: [
    { required: true, message: '请输入店铺名', trigger: 'blur' },
    { type: 'string', min: 1, max: 10, message: '长度1-10', trigger: 'blur' },
  ],
})

watch(id, (newVal, oldVal) => {
  if (newVal == 0) return
  const getShopByIdResult = getShopById({ id: newVal })
  getShopByIdResult.then((res) => {
    if (res.code !== 200) {
      return ElMessage({
        showClose: true,
        message: res.message,
        type: 'error',
      })
    }
    shopForm.name = res.data.name
  })
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  immediate: true
})


// 编辑店铺
const shopEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const deliverOrderByIdAndJwtResult = deliverOrderByIdAndJwt({ id: id, trackingNumber: orderForm.trackingNumber })
      deliverOrderByIdAndJwtResult.then((res) => {
        if (res.code !== 200) {
          return ElMessage({
            showClose: true,
            message: res.message,
            type: 'error',
          })
        }
        return ElMessage({
          showClose: true,
          message: "发货成功",
          type: 'error',
        })
      })
    }
  })
}
</script>
  
<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}

.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>
  